package com.yxplearn.mybatisplus.dao;

import com.yxplearn.mybatisplus.dao.core.EntryType;
import com.yxplearn.mybatisplus.dao.core.Property;
import com.yxplearn.mybatisplus.dao.entry.UserPojo;
import com.yxplearn.mybatisplus.dao.util.JdbcUtil;
import com.yxplearn.mybatisplus.dao.util.SqlOperation;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BaseDao<T> {

    private static BaseDao instance = new BaseDao();
    private static JdbcUtil jdbcUtil = new JdbcUtil();

    public static BaseDao getInstance() {
        return instance;
    }

    public void init() {
        jdbcUtil.initDataSource();
        EntryType.initPropertiesMap(UserPojo.class);
    }

    public <T> T queryByPrimaryKey(Class<T> clazz, final int primaryKey) {
        EntryType entryType = EntryType.entryTypeMap.get(clazz);
        String selectAllSql = entryType.getSelectAllSql();
        SqlOperation sqlOperation = new SqlOperation() {
            @Override
            public void fillPrimaryKey(PreparedStatement ps) {
                entryType.getPrimaryKeyFiled().setValue(ps, primaryKey);
            }
        };
        sqlOperation.setEntryType(entryType);
        sqlOperation.setSql(selectAllSql);
        return (T)jdbcUtil.executeQuery(sqlOperation);
    }

}
